from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status
from rest_framework import exceptions

def custom_exception_handler(exc, context):
    """自定义异常处理"""
    ret = {'msg': 'success', 'errors': '', 'code': '', 'data': ''}
    response = exception_handler(exc, context)
    print(response)
    if response is None:
        ret['errors'] = '服务器错误'
        return Response(ret, status=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=True)
    if isinstance(exc, exceptions.AuthenticationFailed):
        ret['errors'] = exc.detail
        return Response(ret, status=status.HTTP_403_FORBIDDEN)
    elif isinstance(exc, exceptions.ValidationError):
        # 序列化器验证不通过
        for index, key in enumerate(response.data):
            if index == 0:
                ret['errors'] = key + response.data[key][0]
                return Response(ret, status=response.status_code)

    return response